package wordcount;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class wordcount {
	private HashMap<String, Integer> count = new HashMap<String, Integer>();
	private List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(count.entrySet());
	// 将了不起的盖茨比通过stringbuffer读取到一个字符串中
	private String readFromTxt(String filepath) throws Exception {
		Reader reader = null;
		try {
			StringBuffer buf = new StringBuffer();
			char[] chars = new char[1024];
			reader = new FileReader(filepath);
			int readed = reader.read(chars);
			while (readed != -1) {
				buf.append(chars, 0, readed);
				readed = reader.read(chars);
			}
			return buf.toString();
		} finally {
			reader.close();
			;
		}
	}

	// 将书本内容通过空格符分割
	private String[] splitContentToChapter(String content) {
		String contents[] = content.split("\\s+");
		return contents;
	}

	// 将单词放入hashmap中并统计词频,同时进行排序
	private List putin_and_sort(String[] content) {
		for (int i = 0; i < content.length; i++) {
			if (count.containsKey(content[i])) {
				count.put(content[i], count.get(content[i]) + 1);
			}
			else {
				count.put(content[i], 1);
			}
		}
		for(Map.Entry<String, Integer> entry : count.entrySet()){
             list.add(entry); //将map中的元素放入list中
        }
		list.sort(new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}
		});
		return list;
	}

	// 输出结果
	public void output(String sourpath,String destpath) throws Exception {
		list=putin_and_sort(splitContentToChapter(readFromTxt(sourpath)));
		File file = new File(destpath);
		if (!file.exists())
			file.createNewFile();
		PrintWriter pw = new PrintWriter(destpath);
		for(int i = 0; i < list.size(); i++){
			pw.write(((Entry<String, Integer>) list.get(i)).getKey() + " "
					+ ((Entry<String, Integer>) list.get(i)).getValue()+ "\r\n");
			System.out.println(((Entry<String, Integer>) list.get(i)).getKey() + " "
					+ ((Entry<String, Integer>) list.get(i)).getValue());
		}
		pw.close();
	}

}